#include "key_input.h"
#include "bsp_delay.h"

// 开发板有用户按键三个，key1---PA4 key2---PA5 key3----PA6
// PA6用作了串口2的功能
// 所以这里只用Key1 Key2


static void key_input_exti_nvic_init(IRQn_Type IRQChannel,FunctionalState state)
{
    NVIC_InitType NVIC_InitStructure;
    /* Set key input interrupt priority */
    NVIC_InitStructure.NVIC_IRQChannel                   = IRQChannel;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority        = NVIC_SUB_PRIORITY_1;
    NVIC_InitStructure.NVIC_IRQChannelCmd                = state;
    NVIC_Initializes(&NVIC_InitStructure);
}


static void key_input_exti_line_init(uint8_t EXTI_line_source, uint32_t pin_source ,uint32_t EXTI_Line)
{
    EXTI_InitType EXTI_InitStructure;
    /* Configure key EXTI Line to key input Pin */
    GPIO_EXTI_Line_Set(EXTI_line_source, pin_source);

    /* Configure key EXTI line */
    EXTI_InitStructure.EXTI_Line    = EXTI_Line;
    EXTI_InitStructure.EXTI_Mode    = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; 
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Peripheral_Initializes(&EXTI_InitStructure);
}

static void key_input_exti_gpio_init(GPIO_Module* GPIOx, uint16_t Pin)
{
    GPIO_InitType GPIO_InitStructure;

    /* Enable the GPIO Clock */
    if (GPIOx == GPIOA)
    {
        RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOA);
		RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO);
    }
    else if (GPIOx == GPIOB)
    {
		RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOB);
		RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO);
    }
    else if (GPIOx == GPIOC)
    {
		RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOC);
		RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO);
    }
    else if (GPIOx == GPIOD)
    {
		RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOD);
		RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO);		
    }
    else
    {
        return;
    }

    if (Pin <= GPIO_PIN_ALL)
    {
        GPIO_Structure_Initialize(&GPIO_InitStructure);
        GPIO_InitStructure.Pin          = Pin;
        GPIO_InitStructure.GPIO_Pull    = GPIO_PULL_UP;
        GPIO_Peripheral_Initialize(GPIOx, &GPIO_InitStructure);
    }

}

// extern func 
void key_input_init(void)
{
    // init key1
    key_input_exti_gpio_init(KEY1_INPUT_PORT,KEY1_INPUT_PIN);
    key_input_exti_line_init(KEY1_INPUT_PORT_SOURCE,KEY1_INPUT_PIN_SOURCE,KEY1_INPUT_EXTI_LINE);
    key_input_exti_nvic_init(KEY1_INPUT_IRQn,ENABLE);
    // init key2
    key_input_exti_gpio_init(KEY2_INPUT_PORT,KEY2_INPUT_PIN);
    key_input_exti_line_init(KEY2_INPUT_PORT_SOURCE,KEY2_INPUT_PIN_SOURCE,KEY2_INPUT_EXTI_LINE);
    key_input_exti_nvic_init(KEY2_INPUT_IRQn,ENABLE);

}

void key_input_exit_nvic_disable()
{
	key_input_exti_nvic_init(KEY1_INPUT_IRQn,DISABLE);
	key_input_exti_nvic_init(KEY2_INPUT_IRQn,DISABLE);
}


